import uvicorn
from fastapi import FastAPI, Query
from common.tools import Tools
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:8080"],  # 允许的前端域名
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"],  # 允许所有HTTP头
)


# 模拟离线查询方法
def offline_query(size: int):
    sql = f'SELECT * FROM `system_sms_code` LIMIT 0,{size}'
    data = Tools().db(sql, database='test-r')
    return [{"id": i[0], "phone": i[1], "code": i[2]} for i in data]


# 模拟在线查询方法
def online_query(size: int):
    sql = f'SELECT * FROM `system_sms_code` LIMIT 0,{size}'
    data = Tools().db(sql, database='test-a')

    return [{"id": i[0], "phone": i[1], "code": i[2]} for i in data]


@app.get("/data")
async def get_data(isonline: bool = Query(True, description="是否进行在线查询"),
                   size: int = Query(10, description="每页条数")):
    if isonline:
        result = online_query(size)
    else:
        result = offline_query(size)

    return {"data": result}


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
